package com.studyyoun.android.nonghe.msg.fragment;
/**
 * Created by zhaolong on 2017/10/18.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 */

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidlongs.pullrefreshrecyclerylib.common.PullRecyclerViewUtils;
import com.androidlongs.pullrefreshrecyclerylib.inter.PullRecyclerViewLinserner;
import com.androidlongs.pullrefreshrecyclerylib.inter.PullRecyclerViewOnItemClickLinserner;
import com.androidlongs.pullrefreshrecyclerylib.model.PullRecyclerMoreStatueModel;
import com.studyyoun.android.androidcommonbaselibrary.fragment.CommonBaseFragment;
import com.studyyoun.android.androidcommonbaselibrary.glide.CommonGlideUtils;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.callback.OkhttpCommonCallBack;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.client.OkhttpCommonClient;
import com.studyyoun.android.androidcommonbaselibrary.utils.DateUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.LogUtils;
import com.studyyoun.android.nonghe.R;
import com.studyyoun.android.nonghe.http.HttpUrlHelper;
import com.studyyoun.android.nonghe.msg.activity.MsgDetaileActivity;
import com.studyyoun.android.nonghe.msg.model.MsgModel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * class infation
 */
public class MsgItemMorningFragment extends CommonBaseFragment {

    private LinearLayout mContentLayout;
    private PullRecyclerViewUtils mPullRecyclerViewUtils;
    private List<PullRecyclerMoreStatueModel> mCommonMsgModelList = new ArrayList<>();

    public MsgItemMorningFragment() {
        LogUtils.d("MsgItemMorningFragment constory ");
    }

    @Override
    public void onAttach(Context context) {
        //当fragment 第一次与 Activity 产生关联时调用，以后不再调用
        super.onAttach(context);
        LogUtils.d(" Fragment onAttach() 方法执行！");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //在 onAttach 执行完后会立刻调用此方法，通常被用于读取保存的状态值，获取或者初始化一些数据，
        // 但是该方法不执行，窗口是不会显示的，因此如果获取的数据需要访问网络，最好新开线程。
        super.onCreate(savedInstanceState);
        LogUtils.d(" Fragment onCreate() 方法执行！");
    }

    @Override
    protected int getCommonLayoutId() {
        return R.layout.fragment_item_mornig_layout;
    }

    @Override
    protected void commonInitView(View view) {
        mContentLayout = view.findViewById(R.id.ll_item_msg_mornig);
        //初始化
        mPullRecyclerViewUtils = PullRecyclerViewUtils.getInstance();

        //3初始化Recyclerview
        /**
         * 参数一 this Context实例
         * 参数二 单一布局模式条目布局ID
         * 参数三 数据集合
         * 参数四 回调监听
         */
        RelativeLayout relativeLayout = mPullRecyclerViewUtils.setRecyclerViewFunction(mContext, -1, mCommonMsgModelList, mPullRecclerLinserner, mItemClickLinserner);

        //4相关设置

        //下拉刷新和上拉加载更多模式
        mPullRecyclerViewUtils.setRecyclerviewStatue(PullRecyclerViewUtils.RECYCLRYVIEW_STATUE.PULL_AND_UP);

        mPullRecyclerViewUtils.setFirstDefaultPageType(PullRecyclerViewUtils.SHOW_DEFAUTLE_PAGE_TYPE.LOADING);

        mPullRecyclerViewUtils.setPullScrollRecyclerLiserner(mOnPullRecyclerviewScrollLiserner);
        //5将recyclerview添加到当前显示的页面中
        mContentLayout.addView(relativeLayout);

        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) relativeLayout.getLayoutParams();
        if (layoutParams != null) {
            //layoutParams.setMargins(layoutParams.leftMargin,layoutParams.topMargin,layoutParams.rightMargin,30);
        }
    }

    @Override
    protected void commonFunction() {

        LogUtils.d("msgItemMorningFragment commonFunction");
    }

    @Override
    protected void commonDelayFunction() {
        loadingNetDatas();
    }


    private int mPageIndex = 0;
    private int mPageSize = 50;
    private LOADING_TYPE mCurrentLoadingType = LOADING_TYPE.NORMAL;

    private enum LOADING_TYPE {
        PULL,
        UP,
        NORMAL
    }

    public void loadingNetDatas() {

        LogUtils.d("msgItemMorningFragment loadingNetDatas");

        if (mCurrentLoadingType == LOADING_TYPE.NORMAL) {
            if (mCommonMsgModelList.size() > 0) {
                return;
            }
        }

        if (mPullRecyclerViewUtils == null) {
            return;
        }
        mPullRecyclerViewUtils.startLoadingAnimation();
        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
        key.put("pageIndex", String.valueOf(mPageIndex));
        key.put("pageSize", String.valueOf(mPageSize));

        String url = HttpUrlHelper.sGetMsgAllListUrl;

        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack(MsgModel.class) {
            @Override
            public void onSuccess(Object obj) {

                mPullRecyclerViewUtils.stopLoadingAnimation();
                if (obj != null) {
                    List<MsgModel> modelList = (List<MsgModel>) obj;
                    for (int i = 0; i < modelList.size(); i++) {
                        PullRecyclerMoreStatueModel pullRecyclerMoreStatueModel = new PullRecyclerMoreStatueModel();

                        pullRecyclerMoreStatueModel.model = modelList.get(i);

                        if (i % 3 == 0) {
                            pullRecyclerMoreStatueModel.itemType = 1;
                            pullRecyclerMoreStatueModel.itemLayoutId = R.layout.item_msg_mornig_text_layout;
                        } else {
                            pullRecyclerMoreStatueModel.itemType = 2;
                            pullRecyclerMoreStatueModel.itemLayoutId = R.layout.item_msg_mornig_layout;
                        }
                        mCommonMsgModelList.add(pullRecyclerMoreStatueModel);
                    }
                    mPullRecyclerViewUtils.setLoadingDataList(mCommonMsgModelList);

                } else {
                    mPullRecyclerViewUtils.setLoadingDataList(mCommonMsgModelList);
                }
            }

            @Override
            public void onFaile(Object obj) {
                mPullRecyclerViewUtils.stopLoadingAnimation();
                if (mCurrentLoadingType == LOADING_TYPE.PULL) {
                    mPullRecyclerViewUtils.setLoadingDataList(null);
                } else if (mCurrentLoadingType == LOADING_TYPE.UP) {
                    mPullRecyclerViewUtils.setLoadingDataList(null);
                } else {
                    mPullRecyclerViewUtils.setLoadingDataList(null);
                }
            }
        });

    }

    private PullRecyclerViewLinserner mPullRecclerLinserner = new PullRecyclerViewLinserner() {
        @Override
        public void loadMoreData() {
            mPageIndex++;
            loadingNetDatas();
        }

        @Override
        public void loadingRefresDataFunction() {

            mPageIndex = 0;
            mCommonMsgModelList.clear();
            loadingNetDatas();
        }

        @Override
        public void setViewDatas(View itemView, int position, int itemType, Object object) {

            PullRecyclerMoreStatueModel pullRecyclerMoreStatueModel = (PullRecyclerMoreStatueModel) object;

            if (pullRecyclerMoreStatueModel.itemType == 2 || pullRecyclerMoreStatueModel.itemType == 1) {

                MsgModel msgModel = (MsgModel) pullRecyclerMoreStatueModel.model;

                TextView titleTextView = itemView.findViewById(R.id.tv_msg_title);
                titleTextView.setText(msgModel.getMsgTitle());

                if (pullRecyclerMoreStatueModel.itemType == 1) {
                    TextView contentTextView = itemView.findViewById(R.id.tv_msg_content);
                    contentTextView.setText(Html.fromHtml(msgModel.getMsgRemark()));
                    contentTextView.setClickable(true);
                    contentTextView.setMovementMethod(LinkMovementMethod.getInstance());
                }

                if (pullRecyclerMoreStatueModel.itemType == 2) {
                    ImageView imageView = itemView.findViewById(R.id.iv_msg_content);

                    String imageUrl = msgModel.getImgUrl();
                    String msgModelImgUrl = msgModel.getImgUrl();
                    if (!TextUtils.isEmpty(msgModelImgUrl)) {
                        if (msgModelImgUrl.contains(",")) {
                            String[] imageUrlSplit = msgModelImgUrl.split(",");
                            if (imageUrlSplit != null && imageUrlSplit.length > 0) {
                                imageUrl = imageUrlSplit[0];
                            }
                        }
                    }
                    CommonGlideUtils.showImageView(mContext, R.mipmap.default_lar_pic, HttpUrlHelper.BaseImageHost + imageUrl, imageView);
                }


                TextView msgOtherTextView = itemView.findViewById(R.id.tv_item_msg_other);

                String pariseCount = "0";
                String commentCount = "0";
                String readCount = String.valueOf(msgModel.readCount);

                if (msgModel.pariseList != null) {
                    pariseCount = String.valueOf(msgModel.pariseList.size());
                }
                if (msgModel.commentList != null) {
                    commentCount = String.valueOf(msgModel.commentList.size());
                }


                TextView timeTextView = itemView.findViewById(R.id.tv_item_msg_time);
                try {
                    timeTextView.setText(DateUtils.getInstance().formatTime(Long.valueOf(msgModel.getCreateTime()), "yyyy-MM-dd"));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

                StringBuilder stringBuilder = new StringBuilder(pariseCount);
                stringBuilder.append("赞");
                stringBuilder.append(" • ");
                stringBuilder.append(commentCount);
                stringBuilder.append("评论");
                stringBuilder.append(" • ");
                stringBuilder.append(readCount);
                stringBuilder.append("阅读");

                msgOtherTextView.setText(stringBuilder.toString());
            }
        }
    };

    private PullRecyclerViewOnItemClickLinserner mItemClickLinserner = new PullRecyclerViewOnItemClickLinserner() {
        @Override
        public void setonItemClick(int position, int itemType, Object object) {

            PullRecyclerMoreStatueModel moreStatueModel = (PullRecyclerMoreStatueModel) object;
            itemType = moreStatueModel.itemType;
            if (itemType == 1 || itemType == 2) {
                MsgModel msgModel = (MsgModel) moreStatueModel.model;
                LogUtils.d("msg click ");
                Intent intent = new Intent(mContext, MsgDetaileActivity.class);
                intent.putExtra("msgModel", msgModel);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        }
    };

    private PullRecyclerViewUtils.OnPullRecyclerviewScrollLiserner mOnPullRecyclerviewScrollLiserner = new PullRecyclerViewUtils.OnPullRecyclerviewScrollLiserner() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy, LinearLayoutManager mLinearLayoutManager) {

        }
    };
}
